var app = getApp();
var api = require('../../api.js');
var timer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current_no:0,
    exam_id:0,
    question_list:[],
    question_no:1,
    test_anwser:[],
    indicatorDots: false,
    autoplay1: false,
    interval1: 500,
    duration: 200,
    startdo_time:0,
    flag: true,
    pusher: false,
    test_time:30,
    paper_id:0,
    AUTH:true,
    showAds:false,
  },
  hiddenAds(){
    this.setData({
      showAds:true
    })
  },
  radioChange: function (e) {
    var page =this
    console.log(e);
    console.log('radio发生change事件，携带value值为：', e.currentTarget.dataset.key)

    var question = page.data.question_list;
    var test = page.data.test_anwser;
    let value = e.currentTarget.dataset.key;
    let index = e.currentTarget.dataset.index;
    //let no = question[index].question_number;
      test.push({
        value: value,
        no: question[index].question_number
      });
    //多选
    if (question[index].answer.length>1){
      if (question[index]['checked']) {
        if (question[index]['checked'].indexOf(value) == -1) {
          question[index]['checked'].push(value);
        } else {
          splice(question[index]['checked'].indexOf(value), 1, question[index]['checked'])
        }
      } else {
        question[index]['checked'] = [];
        question[index]['checked'].push(value);
      }
    }else{
      //单选
      question[index]['checked'] = [value];
    }
    
    
    this.setData({
      test_anwser:test,
      seleted: "选中的value：" + value,
      question_list: question,
    })
    if (index < page.data.question_list.length - 1 && question[index].answer.length == 1 && page.data.type!=1){
      setTimeout(function () {
        page.setData({
          current_no: index + 1
        })
      }, 500)
      
    }
    if (index == page.data.question_list.length-1){
      wx.showToast({
        title: '只有这么多了',
        icon:'none'
      })
    }
  },
  //下一题
  nextQuestion:function(){
    var page =this
    if (page.data.current_no == page.data.question_list.length - 1) {
      wx.showToast({
        title: '只有这么多了',
        icon: 'none'
      })
    }else{
      page.setData({
        current_no: page.data.current_no + 1
      })

    }
    
  },
  //上一题
  preQuestion:function(){
    var page = this
    if (page.data.current_no ==0) {
      wx.showToast({
        title: '已经是第一题了',
        icon: 'none'
      })
    } else {
      page.setData({
        current_no: page.data.current_no -1
      })
    }
  },
  currentChange:function(e){
    var page =this
    page.setData({
      current_no: e.detail.current
    })
  },
  hiddenContent:function(){
    wx.navigateBack({
      detal:-1
    })
  },

  /***分享收藏**/
  toggleShare: function () {
    var pusher = this.data.pusher;
    this.setData({
      pusher: !this.data.pusher
    })
  },
 
  /***答题卡打开关闭**/
  showcardpop: function () {
    this.setData({ flag: false })
  },

  hidecardpop: function () {
    this.setData({ flag: true })
  },

  /*** 生命周期函数--监听页面加载*/
  onLoad: function (options) {
    //判断登陆
    var rdsession = wx.getStorageSync('rdsession');
    if (!rdsession) {
      //暂存参数
      if (options) {
        wx.setStorageSync("tmp_options", options)
      }
      wx.navigateTo({
        url: '/pages/usersq/usersq',
      })
    }
    if(options){
      wx.setStorageSync("tmp_options", options)
      if (options.paper_id){
        this.setData({
          paper_id: options.paper_id
        })
      }
      if(options.exam_id){
        this.setData({
          exam_id: options.exam_id
        })
      }
      if (options.type) {
        this.setData({
          type: options.type
        })
      }
    }
    this.getPaperDetail()
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    this.setData({
      startdo_time: timestamp
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearTimeout(timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(timer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var user = wx.getStorageSync('user_info');
    this.setData({
      is_share:1
    })
    this.addShare()
    return {
      path: '/pages/test/test?paper_id=' + this.data.paper_id + '&pid=' + user.user_id,
    }
  },
  turnQuestion(e){
    this.setData({
      current_no:e.currentTarget.dataset.index,
      flag:true
    })

  },
  getPaperDetail:function(){
    var page = this;
    wx.showLoading({
      title: '加载中',
    })
    app.request({
      url: api.paper.question_list,
      method: 'POST',
      data: {
        paper_id: page.data.paper_id,
        exam_id: page.data.exam_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            AUTH: res.data.AUTH
          })
          page.setData({
            question_list: res.data.questions,
            paper_info: res.data.paper_info,
            is_collect: res.data.paper_info.is_collect,
            test_time: res.data.paper_info.timelong
          })
          wx.setNavigationBarTitle({
            title: res.data.paper_info.title,
          })
          if (page.data.type != 2 && page.data.paper_info.dolog==1){
            page.setData({
              flag:false
            })
          }
          //检查vip权限
          if(res.data.AUTH == true && !page.data.exam_id && page.data.type==2){
            //倒计时
            page.setCountDown()
          }else{
            // wx.showModal({
            //   title: '提示',
            //   content: '您的VIP等级不符合，请开通VIP',
            //   success(res){
            //     if(res.confirm){
            //       wx.redirectTo({
            //         url: '../buy-vip/buy-vip',
            //       })
            //     }
            //     if(res.cancel){
            //       wx.navigateBack({
            //         delta:1
            //       })
            //     }
            //   }
            // })
          }
          
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  //交卷
  submitPaper:function(){
    var page = this;
    wx.showLoading({
      title: '加载中',
    })
    let question_list = page.data.question_list;
    let post_data=[];
    for(let i in question_list){
      post_data[i]={
        id: question_list[i].id,
        checked: question_list[i].checked ? question_list[i].checked:'',
        answer: question_list[i].answer
      };
      // console.log(i);
      // post_data[i]['id'] = question_list[i].id;
      // post_data[i]['ckecked'] = question_list[i].ckecked;
    }
    app.request({
      url: api.paper.submit_paper,
      method: 'POST',
      data: {
        type:page.data.type,
        paper_data: JSON.stringify(post_data),
        startdo_time: page.data.startdo_time
      },
      success: function (res) {
        if (res.errcode == 0) {
          wx.navigateTo({
            url: '../test-report/test-report?exam_id='+res.data+'&type='+page.data.type,
          })
          
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  collect: function () {
    var page = this;
    wx.showLoading({
      title: '加载中',
    })
    var collect = page.data.is_collect;
    app.request({
      url: api.paper.collect_paper,
      method: 'POST',
      data: {
        paper_id: page.data.paper_id,
        question_id: page.data.question_list[page.data.current_no].id
      },
      success: function (res) {
        if (res.errcode == 0) {
          var question_list = page.data.question_list;
          question_list[page.data.current_no].is_collect = res.data;
          page.setData({
            question_list: question_list
          })
          if (res.data == 0) {
            wx.showToast({
              title: '取消收藏',
            })
          } else {
            wx.showToast({
              title: '收藏成功',
            })
          }
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.errmsg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },

  /**
   * iao
   */
  topay: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })

    app.request({
      url: api.paper.add_order,
      method: "POST",
      data: {
        paper_id: that.data.paper_id
      },
      success: function (response) {
        if (response.errcode == 0) {
          if (response.data.need_pay == 1) {
            that.getPay(response.data.order_id);
          } else {
            that.createExam(response.data.order_id)
          }

        } else {
          wx.showToast({
            title: response.errmsg,
            icon: 'none'
          })
        }

      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  getPay: function (e) {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    app.request({
      url: api.order.get_pay_data,
      method: 'POST',
      data: {
        order_id: e,
        pay_type: 'WECHAT_PAY'
      },
      success: function (result) {
        wx.hideLoading();
        if (result.errcode == 0) {
          var pay_data = result.data;
          wx.requestPayment({
            timeStamp: pay_data.timeStamp,
            nonceStr: pay_data.nonceStr,
            package: pay_data.package,
            signType: pay_data.signType,
            paySign: pay_data.paySign,
            success: function (res) {
              wx.showToast({
                title: '订单支付成功',
                icon: 'success'
              });
              that.getPaperDetail()
            },
            fail: function (res) {
              wx.showToast({
                title: '订单未支付',
                image: '/images/icon-warning.png'
              });
            }
          });
        } else {
          wx.showModal({
            title: '提示',
            content: result.msg,
            showCancel: false
          });
        }
      }
    });
  },
  addShare: function () {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })

    app.request({
      url: api.paper.add_share,
      method: "POST",
      data: {
        paper_id: that.data.paper_id
      },
      success: function (response) {
        if (response.errcode == 0) {
          that.getPaperDetail()
        } else {
          wx.showToast({
            title: response.errmsg,
            icon: 'none'
          })
        }

      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  /**
   * 倒计时
   */
  setCountDown: function () {
    let page = this
    let time = 1;
    let test_time = page.data.test_time
    test_time -= time;
    if (test_time>0){
      let formatTime = page.getFormat(test_time);
      let countDown = `${formatTime.hh}:${formatTime.mm}:${formatTime.ss}`;
      page.setData({
        test_time: test_time,
        formatTime: formatTime,
        countDown: countDown
      });
      timer = setTimeout(page.setCountDown, 1000);
    }else{
      wx.showToast({
        title: '考试时间到',
      })
      page.submitPaper()
      // wx.showModal({
      //   title: '提示',
      //   content: '考试时间结束，确认交卷',
      //   success(res){
      //     if(res.confirm){
            
      //     }
      //   }
      // })
    }
    
  },

  /**
   * 格式化时间
   */
  getFormat: function (msec) {
    let ss = parseInt(msec );
    // let ms = parseInt(msec % 1000);
    let mm = 0;
    let hh = 0;
    if (ss > 60) {
      mm = parseInt(ss / 60);
      ss = parseInt(ss % 60);
      if (mm > 60) {
        hh = parseInt(mm / 60);
        mm = parseInt(mm % 60);
      }
    }
    ss = ss > 9 ? ss : `0${ss}`;
    mm = mm > 9 ? mm : `0${mm}`;
    hh = hh > 9 ? hh : `0${hh}`;
    return { ss, mm, hh };
  }
})